﻿using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
using System;
using System.Transactions;

namespace SoGame.Model
{
    public partial class SoGameDbContext : DbContext
    {
        #region InitializeDatabase
        private class InitializeDatabase : DropCreateDatabaseIfModelChanges<SoGameDbContext> {
            protected override void Seed(SoGameDbContext context)
            {
                using (new TransactionScope(TransactionScopeOption.Suppress)) {
                    context.Database.ExecuteSqlCommand("alter table [dbo].[players] alter column FirstName nvarchar(50) collate SQL_Latin1_General_CP1_CI_AI null");
                    context.Database.ExecuteSqlCommand("alter table [dbo].[players] alter column Name nvarchar(50) collate SQL_Latin1_General_CP1_CI_AI not null");
                }
            }
        }
        #endregion

        public SoGameDbContext() : base()
            //: base(ConfigurationManager.ConnectionStrings["SoGame.Properties.Settings.SoDatabase"].ConnectionString)
        {
            Database.SetInitializer(new InitializeDatabase());
            this.Configuration.LazyLoadingEnabled = true;
        }

        /// <summary>
        /// Gets or sets the players.
        /// </summary>
        /// <value>
        /// The players.
        /// </value>
        public DbSet<Player> Players { get; set; }

        /// <summary>
        /// Gets or sets the game plays.
        /// </summary>
        /// <value>
        /// The game plays.
        /// </value>
        public DbSet<GamePlay> GamePlays { get; set; }

        /// <summary>
        /// Gets or sets the sent mails.
        /// </summary>
        /// <value>
        /// The sent mails.
        /// </value>
        public DbSet<SentMail> SentMails { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<SentMail>().HasKey(t => t.GamePlayID);

            modelBuilder.Entity<GamePlay>()
                .HasOptional(t => t.Player)
                .WithMany(c => c.GamePlays)
                .HasForeignKey(t => t.PlayerID)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<GamePlay>()
                .HasOptional(t => t.SentMail)
                .WithRequired(t => t.GamePlay);
            //modelBuilder.Entity<SentMail>()
            //    .Map(t => t.Properties(p => p.GamePlay));

        }
    }
}
